package com.buhler.iot.task;

import com.buhler.iot.entity.ScriptEntity;
import com.xxdb.data.BasicTable;
import com.xxdb.data.Entity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xxdb.DBConnection;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class WriteTask implements Runnable {


    public WriteTask(DBConnection connection, Queue<ScriptEntity> entities){
        this.connection = connection;
        this.entities = entities;
    }

    private DBConnection connection;


    private Queue<ScriptEntity> entities;

    private  final Logger logger = LoggerFactory.getLogger(WriteTask.class);

    @Override
    public void  run() {
        try{
            while (true){
                try{
                    if(entities.size()==0){
                        return ;
                    }
                    ScriptEntity scriptEntity = entities.remove();
                    String script = scriptEntity.getScript();
                    BasicTable table = scriptEntity.getTable();
                    List<Entity> args = new ArrayList<Entity>(1);
                    args.add(table);
                    String tableName = scriptEntity.getTableName();
                    logger.debug(" table:{} start insert",tableName);
                    connection.run(script,args);
                    logger.debug(" table：{} end   insert",tableName);

                }catch (Exception e){
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            }
        }catch ( Exception exception){
            logger.error(exception.getMessage());
        }
        return ;

    }
}
